package org.lilred.nzbberry.controllers;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.browser.plugin.BrowserContentProviderContext;
import net.rim.device.api.ui.component.Menu;

import org.lilred.nzbberry.http.HttpMultipartRequest;
import org.lilred.nzbberry.plugin.PluginDownloader;
import org.lilred.nzbberry.views.PluginView;
import org.lilred.nzbberry.webservice.SabnzbdActionClient;

public class PluginController extends PageController {
	PluginView pluginView;
	PluginDownloader downloader;
	Timer downloadTimer = new Timer();
	Timer uploadTimer;
	public PluginController(BrowserContentProviderContext context) throws Exception {
		String url = context.getHttpConnection().getURL();
		//If it's a newzbin URL, feed the newzbin ID directly into sabnzbd
		String newzbinString = "http://www.newzbin.com/browse/post/";
		int lastSlashPosition = url.lastIndexOf('/');
		if (url.startsWith(newzbinString)) {
			String newzbinID = url.substring(newzbinString.length(), lastSlashPosition);
			SabnzbdActionClient addClient = new SabnzbdActionClient();
			addClient.addid(newzbinID);
		}
/*		downloader = new PluginDownloader(this, context);
		downloadTimer.schedule(new DownloadStatusTask(), 0, 500);
		try {
			downloader.start();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	*/	
	}
	
	public void downloadComplete(HttpMultipartRequest uploader)  { }
	
	class DownloadStatusTask extends TimerTask { 
		public void run() {
			String status = null;
			switch (downloader.state) {
			case 0: 
				status = "ready";
				break;
			case 1:
				status = "connecting";
				break;
			case 2:
				status = "getting filesize";
				break;
			case 3:
				status = "unknown filesize";
				break;
			case 4:
				status = "transferring";
				break;
			case 5:
				status = "complete";
				break;
			case 6:
				status = "error";
				break;
			}
			pluginView.setDownloadStatus(status);
			if (status == "error") cancel();
		}
	}
	
	class UploadStatusTask extends TimerTask {
		public void run() {
			// TODO Auto-generated method stub
		}
	}

	public Menu makeMenu(Menu menu) {
		// TODO Auto-generated method stub
		return null;
	}	
}
